import React, { useEffect, useState, useRef, useMemo } from 'react';
import { AgGridReact } from '@ag-grid-community/react';
import { ClientSideRowModelModule } from '@ag-grid-community/client-side-row-model';
import { ModuleRegistry } from '@ag-grid-community/core';
import { Button, Modal, Checkbox, Select, message, Card, Tooltip, Row, Col, Space } from 'antd';
import { SettingOutlined, ReloadOutlined, DownloadOutlined } from '@ant-design/icons';
import axios from 'axios';
import './TradesTableAG.css';

ModuleRegistry.registerModules([ClientSideRowModelModule]);

const COLUMN_CONFIG_URL = '/static/config/trades_page.json';
const TRADE_CONFIG_URL = '/static/config/trade_config.json';

// 列头映射（可自定义精简表头）
const headerMap = {
  'trade_id': 'ID',
  'symbol': '品种',
  'open_datetime': '开仓时间',
  'close_datetime': '平仓时间',
  'open_price': '开仓价格',
  'open_qty': '开数',
  'close_price': '平仓价格',
  'close_qty': '平数',
  'direction': '方向',
  'open_order_type': '开仓类型',
  'trade_type': '交易类型',
  'holding_time': '持仓时间',
  'nth_trade': '第几笔',
  'session': '交易时段',
  'point_profit_per_lot': '单手点数',
  'total_points': '总点数',
  'gross_profit': '毛利润',
  'net_profit': '净利润',
  'commission': '佣金',
  'max_floating_profit_points': '最大浮盈点',
  'max_floating_profit_dollars': '最大浮盈$',
  'max_floating_loss_points': '最大浮亏点',
  'max_floating_loss_dollars': '最大浮亏$',
  'entry_reason': '入场理由',
  'exit_reason': '离场理由',
  'stop_loss_price': '止损点位',
  'stop_loss_reason': '止损理由',
  'take_profit_price': '止盈点位',
  'take_profit_reason': '止盈理由',
  'rating': '打分',
  'evaluation': '评价',
  'open_rrr': 'OR',
  'close_rrr': 'CR',
  'fwr': 'FWR',
  'actual_risk': '实际风险',
  'extend': '后续最大盈利',
  'prr': '潜在盈亏比',
};

function TradesTableAG() {
  const [rowData, setRowData] = useState([]);
  const [columnDefs, setColumnDefs] = useState([]);
  const [columnSettings, setColumnSettings] = useState({});
  const [tradeConfig, setTradeConfig] = useState({});
  const [modalVisible, setModalVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const gridRef = useRef();

  // 分组定义
  const columnGroups = [
    {
      group: '基础信息',
      fields: ['ID', '品种', '开仓时间', '平仓时间', '开仓价格', '开数', '平仓价格', '平数', '方向', '开仓类型', '交易类型', '持仓时间', '第几笔', '交易时段']
    },
    {
      group: '盈亏',
      fields: ['单手点数', '总点数', '毛利润', '净利润', '佣金', '最大浮盈点', '最大浮盈$', '最大浮亏点', '最大浮亏$']
    },
    {
      group: '理由/止损止盈',
      fields: ['入场理由', '离场理由', '止损点位', '止损理由', '止盈点位', '止盈理由', '打分', 'OR', 'CR', 'FWR', '实际风险', '后续最大盈利', '潜在盈亏比']
    }
  ];

  // 读取数据和配置
  const fetchAll = async () => {
    setLoading(true);
    try {
      const [tradesRes, colRes, configRes] = await Promise.all([
        axios.get('/trades_api'),
        axios.get(COLUMN_CONFIG_URL),
        axios.get(TRADE_CONFIG_URL)
      ]);

      console.log('tradesRes:', tradesRes.data);
      // console.log('colRes:', colRes.data);
      // console.log('configRes:', configRes.data);

      setRowData(tradesRes.data);
      setColumnSettings(colRes.data.columnSettings || {});
      setTradeConfig(configRes.data || {});
    } catch (error) {
      message.error('数据加载失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchAll();
  }, []);

  // 构建列定义
  useEffect(() => {
    if (!rowData.length) return;

    console.log('rowData[0]:', rowData[0]);
    
    const selectFields = {
      '交易类型': tradeConfig.trade_types || [],
      '入场理由': tradeConfig.entry_reasons || [],
      '离场理由': tradeConfig.exit_reasons || [],
      '止损理由': tradeConfig.stop_loss_reasons || [],
      '止盈理由': tradeConfig.take_profit_reasons || [],
      '打分': ['1', '2', '3', '4', '5'],
    };

    const nonEditableFields = ['品种', '开数', '平数', '方向', '开仓类型', '持仓时间', '交易时段', '第几笔'];

    // 定义数值格式化规则
    const valueFormatter = (params) => {
      const value = parseFloat(params.value);
      if (isNaN(value)) return params.value;
      
      // 日期时间字段格式化
      if (['open_datetime', 'close_datetime'].includes(params.colDef.field)) {
        if (!params.value) return '';
        const date = new Date(params.value);
        if (isNaN(date.getTime())) return params.value;
        return date.toLocaleString('zh-CN', {
          year: '2-digit',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          hour12: false
        }).replace(/\//g, '-');
      }
      
      // 价格字段保留2位小数
      if (['open_price', 'close_price', 'stop_loss_price', 'take_profit_price'].includes(params.colDef.field)) {
        return value.toFixed(2);
      }
      
      // 点数相关字段保留2位小数
      if (['point_profit_per_lot', 'total_points', 'max_floating_profit_points', 'max_floating_loss_points'].includes(params.colDef.field)) {
        return value.toFixed(2);
      }
      
      // 金额字段根据大小决定小数位数
      if (['gross_profit', 'net_profit', 'commission', 'max_floating_profit_dollars', 'max_floating_loss_dollars'].includes(params.colDef.field)) {
        if (Math.abs(value) >= 100) {
          return Math.round(value).toString();
        } else {
          return value.toFixed(1);
        }
      }
      
      return params.value;
    };

    const newColumnDefs = Object.entries(headerMap).map(([field, headerName]) => {
      if (columnSettings[headerName] === false) return null;

      const colDef = {
        field,
        headerName,
        sortable: true,
        filter: true,
        resizable: true,
        pinned: headerName === '品种' ? 'left' : undefined,
        valueFormatter: valueFormatter,
        cellStyle: params => {
          if (field === 'net_profit') {
            const value = parseFloat(params.value);
            if (isNaN(value)) return null;
            if (value >= 500) return { color: '#007bff' };
            if (value > 0) return { color: '#28a745' };
            if (value <= -500) return { color: '#6f42c1' };
            if (value < 0) return { color: '#dc3545' };
          }
          return null;
        }
      };

      if (nonEditableFields.includes(headerName)) {
        colDef.editable = false;
      } else if (Object.keys(selectFields).includes(headerName)) {
        colDef.cellEditor = 'agSelectCellEditor';
        colDef.cellEditorParams = {
          values: selectFields[headerName]
        };
      }

      return colDef;
    }).filter(Boolean);

    setColumnDefs(newColumnDefs);
  }, [rowData, columnSettings, tradeConfig]);

  const defaultColDef = useMemo(() => ({
    flex: 1,
    minWidth: 100,
    editable: true,
    cellEditor: 'agTextCellEditor',
  }), []);

  const handleCellValueChanged = async (params) => {
    const { data, colDef, newValue, oldValue } = params;
    // 如果是恢复旧值的操作，直接返回
    if (params.source && params.source.source === 'api') {
      return;
    }
    
    console.log('handleCellValueChanged', colDef, newValue, oldValue, params.source);
    
    // 检查id是否存在
    if (!data.trade_id) {
      console.error('更新失败：记录ID不存在', data.trade_id);
      message.error('更新失败：记录ID不存在', data.trade_id);
      params.node.setDataValue(colDef.field, params.oldValue, { source: 'api' });
      return;
    }
    
    try {
      // 确保trade_id是字符串类型
      console.log('handleCellValueChanged1 data.trade_id:', data.trade_id);
      const trade_id = String(data.trade_id);
      const requestData = {
        trade_id: trade_id,
        field: colDef.field,
        value: newValue
      };
      console.log('发送更新请求:', requestData);
      console.log('请求数据类型:', {
        trade_id: typeof trade_id,
        field: typeof colDef.field,
        value: typeof newValue
      });
      console.log('请求数据值:', {
        trade_id: trade_id,
        field: colDef.field,
        value: newValue
      });
      
      const response = await axios.post('/update_trade', requestData, {
        headers: {
          'Content-Type': 'application/json'
        }
      });
      if (response.data.success) {
        message.success('更新成功');
      } else {
        console.error('更新失败，服务器响应:', response.data);
        message.error('更新失败: ' + response.data.message);
        console.log('更新失败，恢复旧值1', colDef.field, params.oldValue);
        params.node.setDataValue(colDef.field, params.oldValue, { source: 'api' });
      }
    } catch (error) {
      console.error('更新失败，错误详情:', error.response?.data || error.message);
      message.error('更新失败');
      console.log('更新失败，恢复旧值2', colDef.field, params.oldValue);
      params.node.setDataValue(colDef.field, params.oldValue, { source: 'api' });
    }
  };

  const handleExport = () => {
    gridRef.current.api.exportDataAsCsv({
      fileName: 'trades.csv',
      processCellCallback: params => {
        if (params.column.getColId() === 'net_profit') {
          return params.value ? parseFloat(params.value).toFixed(2) : '';
        }
        return params.value;
      }
    });
  };

  return (
    <div className="trades-table-container">
      <div className="trades-table-toolbar">
        <Space>
          <Button icon={<ReloadOutlined />} onClick={fetchAll} loading={loading}>
            刷新
          </Button>
          <Button icon={<SettingOutlined />} onClick={() => setModalVisible(true)}>
            列设置
          </Button>
          <Button icon={<DownloadOutlined />} onClick={handleExport}>
            导出
          </Button>
        </Space>
      </div>

      <div className="ag-theme-alpine" style={{ height: 'calc(100vh - 120px)', width: '100%' }}>
        <AgGridReact
          ref={gridRef}
          rowData={rowData}
          columnDefs={columnDefs}
          defaultColDef={defaultColDef}
          onCellValueChanged={handleCellValueChanged}
          enableRangeSelection={true}
          suppressRowClickSelection={true}
          rowSelection="multiple"
          pagination={true}
          paginationPageSize={25}
          domLayout="autoHeight"
        />
      </div>

      <Modal
        title="列设置"
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        width={800}
        footer={null}
      >
        <div className="column-settings-container">
          {columnGroups.map((group, groupIndex) => (
            <Card key={groupIndex} title={group.group} className="column-group-card">
              <Row gutter={[16, 16]}>
                {group.fields.map(field => (
                  <Col span={8} key={field}>
                    <Checkbox
                      checked={columnSettings[field] !== false}
                      onChange={e => {
                        setColumnSettings(prev => ({
                          ...prev,
                          [field]: e.target.checked
                        }));
                      }}
                    >
                      {field}
                    </Checkbox>
                  </Col>
                ))}
              </Row>
            </Card>
          ))}
        </div>
      </Modal>
    </div>
  );
}

export default TradesTableAG; 